package com.hulang.sms.sending.utils;


import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.hulang.sms.sending.bean.AliYunSmsPlatform;
import com.hulang.sms.sending.bean.ApiResult;
import com.hulang.sms.sending.bean.SendParam;

import java.util.Map;

public class AliyunSmsUtils {

    /**
     * 发送短信验证码
     *
     * @param sendParam
     * @param template
     * @return
     */
    public static ApiResult smsSendForAliYunWithVerificationCode(SendParam sendParam, AliYunSmsPlatform template) {

        ApiResult result = new ApiResult();
        try {
            System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
            System.setProperty("sun.net.client.defaultReadTimeout", "10000");
            IClientProfile profile = DefaultProfile.getProfile(template.getRegionId(), template.getAccessKeyId(), template.getAccessKeySecret());
            DefaultProfile.addEndpoint(template.getEndpointName(), template.getRegionId(), template.getProduct(), template.getDomain());
            IAcsClient acsClient = new DefaultAcsClient(profile);
            SendSmsRequest request = new SendSmsRequest();
            request.setPhoneNumbers(sendParam.getPhone());
            request.setSignName(template.getSignName());
            request.setTemplateCode(template.getTemplateCode());

            /**
             * 验证码发送格式：  request.setTemplateParam("{\"code\":\"" + code + "\"}");<p>
             * 数据库模板格式：  {"code": "key1"}
             */
            String templateParam = template.getTemplateParam();
            templateParam = templateParam.replace("key1", (String) sendParam.getParam().get("key1"));

            request.setTemplateParam(templateParam);
            SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
            // 后续根据返回码确认发送结果
            String codeStr = sendSmsResponse.getCode();
            if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
                return result.success(codeStr, codeStr);
            } else {
                return result.failed("发送失败", codeStr);
            }
        } catch (Exception e) {
            return result.failed("发送失败", "happen_exception");
        }
    }

    /**
     * 发送短信通知
     *
     * @param sendParam
     * @param template
     * @return
     */
    public static ApiResult smsSendForAliYunWithNotice(SendParam sendParam, AliYunSmsPlatform template) {

        ApiResult result = new ApiResult();
        try {
            System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
            System.setProperty("sun.net.client.defaultReadTimeout", "10000");
            IClientProfile profile = DefaultProfile.getProfile(template.getRegionId(), template.getAccessKeyId(), template.getAccessKeySecret());
            DefaultProfile.addEndpoint(template.getEndpointName(), template.getRegionId(), template.getProduct(), template.getDomain());
            IAcsClient acsClient = new DefaultAcsClient(profile);
            SendSmsRequest request = new SendSmsRequest();
            request.setPhoneNumbers(sendParam.getPhone());
            request.setSignName(template.getSignName());
            request.setTemplateCode(template.getTemplateCode());

            /**
             * 验证码发送格式： request.setTemplateParam("{\"name\":\"Tom\", \"code\":\"123\"}");<p>
             * 数据库模板格式：  {"ApprovalNum": "key1"}
             */
            int paramNum = template.getParamNum();
            String templateParam = template.getTemplateParam();
            String afterDealTemplateParam = dealTemplateParam(sendParam.getParam(), paramNum, templateParam);

            request.setTemplateParam(afterDealTemplateParam);
            SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
            String codeStr = sendSmsResponse.getCode();
            if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
                return result.success(codeStr, codeStr);
            } else {
                return result.failed("发送失败", codeStr);
            }
        } catch (Exception e) {
            return result.failed(e, "happen_exception");
        }
    }

    /**
     * 处理通知短信参数，参数个数不定，约定不多于5个
     *
     * @param param
     * @param paramNum
     * @param templateParam
     * @return
     */
    private static String dealTemplateParam(Map param, int paramNum, String templateParam) {
        switch (paramNum) {
            case 1:
                return templateParam.replace("key1", (String) param.get("key1"));
            case 2:
                return templateParam.replace("key1", (String) param.get("key1")).replace("key2", (String) param.get("key2"));
            case 3:
                return templateParam.replace("key1", (String) param.get("key1")).replace("key2", (String) param.get("key2")).replace("key3", (String) param.get("key3"));
            case 4:
                return templateParam.replace("key1", (String) param.get("key1")).replace("key2", (String) param.get("key2")).replace("key3", (String) param.get("key3")).replace("key4", (String) param.get("key4"));
            case 5:
                return templateParam.replace("key1", (String) param.get("key1")).replace("key2", (String) param.get("key2")).replace("key3", (String) param.get("key3")).replace("key4", (String) param.get("key4")).replace("key5", (String) param.get("key5"));
        }
        return null;
    }
}
